#!/bin/sh

# `nvm install` fails when the default-packages file is invalid,
# but only reports npm failing to install the packages:
# so a failure from nvm_get_default_packages is returned as-is, and an npm failure is 3.

die () { echo "$@" ; exit 1; }

: nvm.sh
\. ../../../nvm.sh

TMP_DIR="$(mktemp -d)" || die 'could not create a temporary directory'
cleanup () {
  case "${TMP_DIR-}" in
    /*) rm -rf "${TMP_DIR}" ;;
  esac
}
trap cleanup 0

# a real executable, since `xargs` cannot run a shell function
NPM_CALLS="${TMP_DIR}/npm-calls"
command printf '#!/bin/sh\necho "$*" >> "%s"\nexit "${NPM_STATUS:-0}"\n' "${NPM_CALLS}" > "${TMP_DIR}/npm" || die 'could not create the npm stub'
chmod +x "${TMP_DIR}/npm" || die 'could not create the npm stub'
PATH="${TMP_DIR}:${PATH}"

check () {
  rm -f "${NPM_CALLS}"
  nvm_install_default_packages >/dev/null 2>&1 && STATUS=0 || STATUS=$?
  [ "${STATUS}" = "$2" ] || die "$1: expected status $2, got >${STATUS}<"
  CALLS="$(cat "${NPM_CALLS}" 2>/dev/null)"
  [ "${CALLS}" = "$3" ] || die "$1: expected npm calls >$3<, got >${CALLS}<"
}

nvm_get_default_packages() { echo 'a b'; }
NPM_STATUS=0
export NPM_STATUS
check 'npm succeeds' 0 'install -g --quiet a b'

NPM_STATUS=1
check 'npm fails' 3 'install -g --quiet a b'

nvm_get_default_packages() { return 0; }
check 'no default packages' 0 ''

nvm_get_default_packages() { echo 'a b'; return 1; }
check 'an invalid default-packages file' 1 ''

nvm_get_default_packages() { return 2; }
check 'an unreadable default-packages file' 2 ''
